package com.yl.config.cors;

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * @Todo
 * @Author jiangtao
 * @CreateBy 2020-02-19 4:38 PM
 * @UpdateBy jiangtao
 * @Version v1.0
 */
@Configurable
public class CorsConfig {

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 1. 允许任何域名使用
        corsConfiguration.addAllowedOrigin("*");
        // 2. 允许任何头
        corsConfiguration.addAllowedHeader("*");
        // 3. 允许任何方法（post、get等）
        corsConfiguration.addAllowedMethod("*");

        //这两句不加不能跨域上传文件，
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.setMaxAge(3600l);

        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }

}
